package org.fintool.http;

import org.fintool.common.Constants;
import org.fintool.common.PropertyUtil;

public class URLMaker {
	static String TEMPLATED_URL=null;
	static int TEMPLATE_CONSTANT_MAX=-1;

	static{
		 TEMPLATED_URL=PropertyUtil.getValue(Constants.URL_TEMPLATED_STRING);
		 TEMPLATE_CONSTANT_MAX=Integer.parseInt(PropertyUtil.getValue(Constants.TEMPLATE_CONSTANT_MAX));
		 if(TEMPLATE_CONSTANT_MAX>=0){
			 for(int i=0;i<=TEMPLATE_CONSTANT_MAX;i++){
				 TEMPLATED_URL= TEMPLATED_URL.replaceFirst("\\("+i+"\\)", PropertyUtil.getValue(Constants.TEMPLATE_CONSTANT_+i));

			 }

			 //http://www.google.com/finance/getprices?q=(SYMBOL)&x=(EXCHANGE)&i=(INTERVAL)&p=(PERIOD)&f=d,c,v,o,h,l&df=cpct&auto=1&ts=(TIMESTAMP)


		 }

	}
	public final String getURL(String stock,String exchange){
	          return getURL(stock,exchange,0l);
	}

	public final String getURL(final String stock,final String exchange,final long  timestampLastUpdated){

		String url=new String(TEMPLATED_URL);

		url=url.replaceFirst("\\("+Constants.SYMBOL+"\\)", stock);
		url=url.replaceFirst("\\("+Constants.EXCHANGE+"\\)", exchange);

		if(PropertyUtil.isDay()){
			url=url.replaceFirst("\\("+Constants.INTERVAL+"\\)", PropertyUtil.getValue(Constants.INTERVAL_DEFAULT_FOR_YEAR));

			//What if the last timestamp is more than a day old
			url=url.replaceFirst("\\("+Constants.PERIOD+"\\)", PropertyUtil.getValue(Constants.MAX_YEARS));
		}else{

			//For seconds
			url=url.replaceFirst("\\("+Constants.INTERVAL+"\\)", PropertyUtil.getValue(Constants.INTERVAL_DEFAULT_FOR_SECONDS));
			url=url.replaceFirst("\\("+Constants.PERIOD+"\\)", PropertyUtil.getValue(Constants.MAX_DAYS));
		}

		//If no Timestamp is sent use todays timestamp
		if(timestampLastUpdated==0l){
		url=url.replaceFirst("\\("+Constants.TIMESTAMP+"\\)", System.currentTimeMillis()+"");
		}else{
			url=url.replaceFirst("\\("+Constants.TIMESTAMP+"\\)",timestampLastUpdated+"");
		}


		System.out.println("URL Maker output-"+url);
		return url;

	}

	public static void main(String[] args) {
		URLMaker urlMaker=new URLMaker();
		System.out.println(urlMaker.getURL("NCM", "ASX"));

	}

}
